#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""  
@Project : pythonProject01
@File : ssh_val.py
@Author : erhu
@Time : 2025/9/9 19:11  
@脚本说明 : 
"""

from .ccolor import Colors
import ipaddress
import threading
import time
import warnings
import paramiko
import logging
import os

warnings.filterwarnings("ignore")
warnings.simplefilter("ignore")

# 屏蔽paramiko日志
logging.getLogger("paramiko").setLevel(logging.CRITICAL)
paramiko.util.log_to_file(os.devnull)
def ssh_connect(host, port=22, username="root", password="root"):
    try:
        ssh_client = paramiko.SSHClient()
        ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

        ssh_client.connect(host, port, username, password, timeout=10)
        ssh_client.get_transport().banner_timeout = 60
        if ssh_client.get_transport().is_active():
            stdin, stdout, stderr = ssh_client.exec_command("echo lyf")
            if "lyf" in stdout.read().decode("utf-8"):
                print(f"[+] {host}:{port} SSH存在弱口令 {Colors.RED_BRIGHT}{Colors.BOLD}[{username} / {password}]{Colors.RESET},可以执行任意命令")
        # 必须有关闭 不然会有大量的ssh连接限制
        ssh_client.close()
    except:
        pass
    finally:
        #延迟
        time.sleep(1)

def ssh_run(host, port, users, password):
    try:
        threads = []
        print("======SSH弱口令漏扫======")
        passwords = [p.strip() for p in password]
        for ip in ipaddress.IPv4Network(host):
            for user in users:
                for passwd in passwords:
                    t = threading.Thread(target=ssh_connect, args=(str(ip), port, user.strip(), passwd.strip()))
                    t.start()
                    threads.append(t)
            for t in threads:
                t.join()
    except:
        pass
